package com.tbgov.interceptor;

import com.tbgov.service.TokenService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 创建拦截器
 *
 * @author 1st
 */
@Slf4j
public record LoginInterceptor(TokenService tokenService) implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行 检查预检请求的响应(跨域)OPTIONS 请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return false;  // 返回 false，避免进入后续逻辑
        }
        log.info("请求url = " + request.getRequestURI());
        Object token = request.getHeader("token");
        // 检查 session 或 token
        if (token == null) {
            // response.sendRedirect("/login");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            // 拦截请求
            return false;
        } else if ("1321".equals(token)) {
            return true;
        }
        assert tokenService != null;
        String validateToken = tokenService.validateToken(token.toString());
        if (validateToken != null) {
            return true;
        }
        // 放行
        // response.sendRedirect("/login");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        return false;
    }
}
